/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import {
  DefaultLawCurveValue,
  getDefaultLawCurveValue,
  getLawCurveFromJSONString,
  isLawCurveValid,
  LawCurve,
  LawCurveButton,
} from '@app-cad/common/law-curve';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useMemo, useState } from 'react';
import { ChildLinearSweepCommandProps } from './types';

type FormData = {
  guide?: pickedLineData;
  surface?: pickedFaceData;
  spline?: pickedLineData;
  leftBound?: pickedVertexData;
  rightBound?: pickedVertexData;

  jsonAngle: string;
  jsonLength1: string;
  jsonLength2: string;
};

type Params = {
  mode: 'ReferenceSurface';
  guide: string;
  surface: string;
  spline?: {
    id?: string;
    leftBound?: string;
    rightBound?: string;
  };
  lineLawAngle: LawCurve;
  lineLawLength1: LawCurve;
  lineLawLength2: LawCurve;
  solution: number;
};

export function ReferenceSurface({
  onClose,
  editDxid,
  props,
}: ChildLinearSweepCommandProps) {
  const initData: FormData = {
    jsonAngle: DefaultLawCurveValue,
    jsonLength1: getDefaultLawCurveValue(10),
    jsonLength2: DefaultLawCurveValue,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  useEffect(() => {
    preview();
  }, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      guide: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
      jsonAngle: {
        title: '角度',
        type: 'string',
      },
      jsonLength1: {
        title: '长度1',
        type: 'string',
      },
      jsonLength2: {
        title: '长度2',
        type: 'string',
      },
      spline: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      leftBound: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertexAndFace,
      },
      rightBound: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertexAndFace,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const {
      guide,
      surface,
      spline,
      lineLawAngle,
      lineLawLength1,
      lineLawLength2,
    }: Params = props.params;

    await initEditDependency(
      [
        guide,
        surface,
        spline?.id,
        spline?.leftBound,
        spline?.rightBound,
      ].filter((id) => id != null),
    );

    setFormData({
      guide: picker.generatePickObjByPickID(guide) as pickedLineData,
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      spline:
        spline?.id &&
        (picker.generatePickObjByPickID(spline?.id) as pickedLineData),
      leftBound:
        spline?.leftBound &&
        (picker.generatePickObjByPickID(spline?.leftBound) as pickedVertexData),
      rightBound:
        spline?.rightBound &&
        (picker.generatePickObjByPickID(
          spline?.rightBound,
        ) as pickedVertexData),
      jsonAngle: JSON.stringify(lineLawAngle),
      jsonLength1: JSON.stringify(lineLawLength1),
      jsonLength2: JSON.stringify(lineLawLength2),
    });

    setSolution(props.params.solution);
  }, [editDxid]);

  const isFormDataValid = () => {
    const lineLawLength1 = getLawCurveFromJSONString(formData.jsonLength1);
    const lineLawLength2 = getLawCurveFromJSONString(formData.jsonLength2);

    // 直线扫掠--参考曲面需要两个法则曲线在同时是常量时 值不能为相反数
    const basicValid =
      formData.guide != null &&
      formData.surface != null &&
      !(
        lineLawLength1.start === -lineLawLength2.start &&
        lineLawLength1.type === 'Constant' &&
        lineLawLength2.type === 'Constant'
      );

    const angleValid = isLawCurveValid(formData.jsonAngle);
    const length1Valid = isLawCurveValid(formData.jsonLength1);
    const length2Valid = isLawCurveValid(formData.jsonLength2);

    return basicValid && angleValid && length1Valid && length2Valid;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-linear-sweep-reference-surface', {
      commandName: 'CreateSurface',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        type: 'LinearSweep',
        a: {
          mode: 'ReferenceSurface',
          guide: formData.guide.edgeId,
          surface: formData.surface.meshId,
          spline: {
            id: formData.spline?.edgeId ?? formData.guide.edgeId,
            leftBound: formData.leftBound?.vertexId,
            rightBound: formData.rightBound?.vertexId,
          },
          lineLawAngle: getLawCurveFromJSONString(formData.jsonAngle),
          lineLawLength1: getLawCurveFromJSONString(formData.jsonLength1),
          lineLawLength2: getLawCurveFromJSONString(formData.jsonLength2),
          solution,
        } as Params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  useAsyncEffect(preview, [solution]);

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      submitLoading={isLoading}
      formData={finalFormData}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        guide: {
          'ui:autofocus': true,
          'ui:placeholder': '请输入引导线',
        },
        surface: {
          'ui:placeholder': '请输入参考曲面',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        jsonAngle: {
          'ui:widget': LawCurveButton,
          'ui:options': {
            suffix: '度',
          },
        },
        jsonLength1: {
          'ui:widget': LawCurveButton,
          'ui:options': {
            suffix: 'mm',
            lawCurveValueStep: 0.1,
          },
        },
        jsonLength2: {
          'ui:widget': LawCurveButton,
          'ui:options': {
            suffix: 'mm',
            lawCurveValueStep: 0.1,
          },
        },
        spline: {
          'ui:placeholder': '脊线(默认是引导线)',
        },
        leftBound: {
          'ui:placeholder': '边界1(选填)',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        rightBound: {
          'ui:placeholder': '边界2(选填)',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      isFormDataValid={isFormDataValid()}
    />
  );
}
